<!-- 项目设备页面 -->
<template>
  <div class="project-container">
    <div v-if="false" class="project-infor-cards">
      <InfoCard :project="selectedProject" />
      <Rule />
      <Schedule />
      <Note />
    </div>
    
    <el-card v-loading="table_Loading" shadow="hover">
      <div class="equip-list">
       
        <div style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 20px;">
          <span class="equip-title_span">设备一览表<span  style="font-size: 16px;color: red" class="equip_text_num">（共{{tableNum}}台设备）</span></span>


          <div
            style="
              display: flex;
              justify-content: flex-end;
              align-items: center;
            "
          >
            <el-button-group class="create-del-equip">
              <el-tooltip content="批量设置设计状态为已完成" placement="top" effect="dark">
                
                <el-button
                class="button_mt_margin_right"
                 color='red'
                 
                  size="small"
                  :icon="DocumentChecked"
                  tag="批量设置设计状态为已完成"
                  @click="clickSendStandChecksSecond2"
                />
              </el-tooltip>



               <el-tooltip content="输出设备信息文件" placement="top" effect="dark">
                
                <el-button
                class="button_mt"
                  type="primary"
                  color="#626aef"
                  size="small"
                  :icon="Download"
                  tag="输出设备信息文件"
                  @click="donwnloadEquipmentLoadInformationTemp"
                />
              </el-tooltip>
              <el-tooltip content="派发安全设计审查派发" placement="top" effect="dark">
                
                <el-button
                class="button_mt"
                  type="primary"
                  color="#f2a36b"
                  size="small"
                  :icon="MessageBox"
                  tag="派发安全设计审查派发"
                  @click="clickSendStandChecksSecond"
                />
              </el-tooltip>
              <el-tooltip content="文件标准化审查派发" placement="top" effect="dark">
                <el-button
                class="button_mt"
                  type="primary"
                  color="#67c23a"
                  size="small"
                  :icon="Tickets"
                  tag="文件标准化审查派发"
                  @click="clickSendStandChecks"
                />
              </el-tooltip>
              
              <el-tooltip content="上传文件" placement="top" effect="dark">
                <el-upload
                              action="#"
                          
                              :http-request="uploadRequest"
                              :show-file-list="false"
                              style="display: inline-block"
                              class="buttonposition">
                              <el-button size="small"  tag="导入设备列表" :icon="Upload" type="primary" class="dr23"></el-button>
                            </el-upload>
              </el-tooltip>
           
              <el-tooltip content="新建设备" placement="top" effect="dark">
                <el-button
                  type="primary"
                  color="#626aef"
                  size="small"
                  :icon="Plus"
                  tag="新建设备"
                  @click="newDioFn()"
                />
              </el-tooltip>
              <el-tooltip content="数据中心新建设备" placement="top" effect="dark">
                <el-button
                  type="primary"
                  color="green"
                  size="small"
                  :icon="CirclePlus"
                  tag="获取数据中心设备"
                  @click="newDioFn('center')"
                />
              </el-tooltip>
              <el-tooltip content="批量删除设备" placement="top" effect="dark">
                <el-button
                  type="danger"
                  size="small"
                  :icon="Delete"
                  @click="deleteEquipment"
                />
              </el-tooltip>
              <el-tooltip content="下载上传文件模板" placement="top" effect="dark">
                <el-button
                class="button_mt"
                  type="primary"
                  color="#67c23a"
                  size="small"
                  :icon="Download"
                  tag="下载上传文件模板"
                  @click="downLoadFiles"
                />
              </el-tooltip>
            </el-button-group>
          </div>
        </div>
        <!-- <EquipList /> -->
        <EquipList :custom_att1_val_option='custom_att1_val_option'  :Myproj_oid='projectStore.projectInfo.proj_oid' :tableHeaderStr='tableHeader' @tableDataSend="tableDataSend" :approver_class='approver_class' :auditor_class='auditor_class' :equip_checker_class='equip_checker_class' :equip_designer_class='equip_designer_class' :installation_mode_class='installation_mode_class' :equipEquip_class="equipEquip_class" :equipOptions="equipOptions" :nameOptions="nameOptions" :equipEquip_no="equipEquip_no" @tableList="tableList" @SelectMajorFn="SelectMajorFn" :equipments="equipments" />
      </div>
    </el-card>

    <el-dialog
    @close="closeFrom(destEquipInfoRef)"
      :title="showCenter?'新建设备':'从数据中心获取设备'"
      v-model="newDio"
      width="25%"
    >
      <el-form
        ref="destEquipInfoRef"
        size="small"
        :model="destEquipInfo"
        :rules="destEquipInfoRules"
        label-width="75px"
      >
        <el-form-item label="主项代号" prop="unit_oid">
          <el-select
            size="small"
            style="width: 100%"
            v-model="destEquipInfo.unit_oid"
            placeholder="请选择主项代号"
          >
            <el-option
              v-for="(item, index) in unit_oidOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="showCenter" label="图纸阶段" prop="equip_class">
          <el-select-v2
            style="width: 100%"
            filterable
            :options="[
              { value: '施工图', label: '施工图' },
              { value: '工程图', label: '工程图' },
            
            ]"
            size="small"
            placeholder="请输入图纸阶段"
            v-model="destEquipInfo.drawing_stage"
          >
          </el-select-v2>
        </el-form-item>
        <el-form-item v-if="showCenter" label="位号" prop="equip_no">
          <el-input
            size="small"
            v-model="destEquipInfo.equip_no"
            placeholder="请输入位号"
          />
        </el-form-item>
        <el-form-item v-if="showCenter" label="设备名称" prop="equip_name">
          <el-input
            size="small"
            v-model="destEquipInfo.equip_name"
            placeholder="请输入设备名称"
          />
        </el-form-item>
        
        <el-form-item v-if="showCenter" label="设备类型" prop="equip_class">
          <el-select-v2
            style="width: 100%"
            filterable
            :options="[
              { value: '换热器', label: '换热器' },
              { value: '容器', label: '容器' },
              { value: '塔器', label: '塔器' },
              { value: '反应器', label: '反应器' },
              { value: '大型储罐', label: '大型储罐' },
              { value: '球罐', label: '球罐' },
              { value: '固体料仓', label: '固体料仓' },
              
            ]"
            size="small"
            placeholder="请输入设备类型"
            v-model="destEquipInfo.equip_class"
          >
          </el-select-v2>
        </el-form-item>
        <el-form-item v-if="showCenter" label="安装方式" prop="installation_mode">
          <el-select-v2
            style="width: 100%"
            filterable
            :options="[
              { value: '鞍座', label: '鞍座' },
              { value: '裙座', label: '裙座' },
              { value: '耳座', label: '耳座' },
              { value: '刚性环', label: '刚性环' },
              { value: '支腿', label: '支腿' },
              { value: '支承式', label: '支承式' },
              { value: '裙式支座', label: '裙式支座' },
              { value: '短裙式支座', label: '短裙式支座' },
              { value: '刚性环支座', label: '刚性环支座' },
              { value: '耳式支座', label: '耳式支座' },
            ]"
            size="small"
            placeholder="请输入安装方式"
            v-model="destEquipInfo.installation_mode"
          >
          </el-select-v2>
        </el-form-item>
        <el-form-item v-if="showCenter" label="设备图号" prop="equip_dwg_no">
          <el-input
            size="small"
            v-model="destEquipInfo.equip_dwg_no"
            placeholder="请输入设备图号"
          />
        </el-form-item>
        <el-form-item v-if="showCenter" label="设备类别" prop="vessel_type">
        
          <el-select style="width: 100%" size="small" placeholder="请输入设备类别"   v-model="destEquipInfo.vessel_type" filterable>
            <el-option
             v-for="(item,index) in [
             {
                    value: 'Ⅰ',
                    label: 'Ⅰ',
                  },
                  {
                    value: 'Ⅱ',
                    label: 'Ⅱ',
                  },
                  {
                    value: 'Ⅲ',
                    label: 'Ⅲ',
                  },
 
                  {
                    value: 'I/SAD',
                    label: 'I/SAD',
                  },
                  {
                    value: 'II/SAD',
                    label: 'II/SAD',
                  },
                  {
                    value: 'III/SAD',
                    label: 'III/SAD',
                  },


                   {
                    value: '类外',
                    label: '类外',
                  },
             ]"
             :key="index"
             :label="item.label"
             :value="item.value"
            >

            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="showCenter" label="台数" prop="equip_count">
          <el-input
            type="number"
            size="small"
            v-model="destEquipInfo.equip_count"
            placeholder="请输入台数"
          />
        </el-form-item>
        <el-form-item v-if="showCenter" label="空设备重量" prop="equip_dry_weight">
          <el-input
            type="number"
            size="small"
            v-model="destEquipInfo.equip_dry_weight"
            placeholder="请输入重量"
          />
        </el-form-item>
        <el-form-item v-if="showCenter" label="特材重量" prop="special_material_weight">
          <el-input
            type="number"
            size="small"
            v-model="destEquipInfo.special_material_weight"
            placeholder="请输入重量"
          />
        </el-form-item>
        <el-form-item v-if="showCenter" label="设计人" prop="equip_designer">
     
          <el-select
           :filter-method="matchFruitFirst"
          clearable
            style="width: 100%"
            filterable
           
             
            size="small"
            placeholder="请输入设计人"
            v-model="destEquipInfo.equip_designer"
          >
          <el-option
         
           :label="item.label"
           :value="item.value"
           v-for="(item,index) in equip_designerOptions_PY"
           :key="index"
          >

          </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="showCenter" label="校核人" prop="equip_checker">
          <el-select
           :filter-method="matchFruitSecond"
          clearable
         
            style="width: 100%"
            filterable
          
            size="small"
            placeholder="请输入校核人"
            v-model="destEquipInfo.equip_checker"
          >

          <el-option
         
           :label="item.label"
           :value="item.value"
           v-for="(item,index) in equip_checkerOptions_PY"
           :key="index"
          >

          </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="showCenter" label="审批人" prop="auditor">
          <el-select
           :filter-method="matchFruitThird"
           clearable
         
            style="width: 100%"
            filterable
          
            size="small"
            placeholder="请输入审批人"
            v-model="destEquipInfo.auditor"
          >
          <el-option
         
         :label="item.label"
         :value="item.value"
         v-for="(item,index) in auditorOptions_PY"
         :key="index"
        >

        </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="showCenter" label="审定人" prop="approver">
          <el-select
           :filter-method="matchFruitFour"
           clearable
         
            style="width: 100%"
            filterable
           
            size="small"
            placeholder="请输入审定人"
            v-model="destEquipInfo.approver"
          >
          <el-option
         
         :label="item.label"
         :value="item.value"
         v-for="(item,index) in approverOptions_PY"
         :key="index"
        >

        </el-option>
          </el-select>
        </el-form-item>
        
        <!-- <el-form-item label="条件发送时间" prop="condition_iss_time">
			<el-date-picker
			style="width: 100%;"
        v-model="destEquipInfo.condition_iss_time"
        type="datetime"
        placeholder="选择条件发送时间"
		value-format="yyyy-MM-dd HH:mm:ss"
        format="yyyy-MM-dd HH:mm:ss"
        >
		</el-date-picker>"
     
         
        </el-form-item> -->
        <el-form-item>
          <div style="width: 100%; display: flex; flex-direction: row-reverse">
            <el-button @click="newDio = false">取 消</el-button>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <el-button type="primary" @click="handleCopyEquip(destEquipInfoRef)"
              >确 定</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>



    <el-dialog @close="closeDio" style="position: relative;" class='my_send_checks' v-model="dialogSendStandChecks" title="" width="35%">
      <!-- <img class='img_hualu' src='../../assets/img/hualu.png'/> -->
      <div style="    display: flex;
    flex-wrap: wrap;">
      <div style="margin-bottom: 10px;width: 50%;"><span style="font-weight: bolder;">项目代号：</span><el-tag type="danger">{{ projectStore.projectInfo.proj_no }}</el-tag></div>
     
      <div style="margin-bottom: 10px;width: 50%;"><span style="font-weight: bolder;">项目名称：</span> <el-tag type="success">{{ projectStore.projectInfo.proj_name }}</el-tag></div>
   
   
      <div style="margin-bottom: 10px;width: 50%;">
      <span style="font-weight: bolder;">审查人&nbsp;&nbsp; ：</span>
      <el-select :filter-method="matchFruit" collapse-tags-tooltip collapse-tags  placeholder="请选择" size="small" multiple filterable clearable v-model="sendDataCheck">
        <el-option v-for="(item,index) in sendDataCheckOptions_py"  :key="index" :label="item.label" :value="item.value">
 
        </el-option>
      </el-select>
    </div>
    </div>
      <el-table height="400px" size="small" :data="SendStandChecksTableData">
      <el-table-column property="equip_name" label="设备名称" />
      <el-table-column property="equip_no" label="设备位号" />
      <el-table-column property="equip_class" label="设备类型" />
      <el-table-column property="installation_mode" label="安装方式" />
    </el-table>
    <div style="margin-top: 30px;display: flex;justify-content: space-between;align-items:center">
     
    <div>
      <el-button v-if='SendStandChecksTableData.length>0' size="small" type='primary' @click='sendDataCheckClick()'>派发任务</el-button>
     
      <el-button  size="small"  @click='dialogSendStandChecks = false'>取消</el-button>
    </div>
    </div>
  </el-dialog>


  <el-dialog @close="closeDioSecond" style="position: relative;" class='my_send_checks2' v-model="dialogSendStandChecksSecond" title="" width="35%">
      <!-- <img  class='img_hualu' src='../../assets/img/hualu.png'/> -->
      <div style="    display: flex;
    flex-wrap: wrap;">
      <div style="margin-bottom: 10px;width: 50%;"><span style="font-weight: bolder;">项目代号：</span><el-tag type="danger">{{ projectStore.projectInfo.proj_no }}</el-tag></div>
     
      <div style="margin-bottom: 10px;width: 50%;"><span style="font-weight: bolder;">项目名称：</span> <el-tag type="success">{{ projectStore.projectInfo.proj_name }}</el-tag></div>
       
      <div style="margin-bottom: 10px;display: flex;align-items: center;width: 50%;"><span style="font-weight: bolder;">专业名称：</span>    <el-select-v2
           size='small'
           style="width:50%"
            v-model="proName"
            placeholder="请选择专业名称"
          
            :options="[
              {
                value:'机修专业',
                label:'机修专业'
              },
              // {
              //   value:'粉体专业',
              //   label:'粉体专业'
              // },
              {
                value:'设备、工业炉专业',
                label:'设备、工业炉专业'
              },

            ]"
            
           >
           </el-select-v2>
 </div>


 <div style="margin-bottom: 10px;width: 50%;">
      <span style="font-weight: bolder;">审查人&nbsp;&nbsp;：</span>
      <el-select :filter-method="matchFruit"  collapse-tags-tooltip collapse-tags  placeholder="请选择" size="small"  filterable clearable v-model="sendDataCheckSecond">
        <el-option v-for="(item,index) in sendDataCheckOptions_py"  :key="index" :label="item.label" :value="item.value">
 
        </el-option>
      </el-select>
    </div>
    </div>
      <el-table v-if="showTableBottom" height="400px" size="small" :data="SendStandChecksTableData">
      <el-table-column property="equip_name" label="设备名称" />
      <el-table-column property="equip_no" label="设备位号" />
      <el-table-column property="equip_class" label="设备类型" />
      <el-table-column property="installation_mode" label="安装方式" />
    </el-table>
    <div v-if="showTableBottom" style="margin-top: 30px;display: flex;justify-content: space-between;align-items:center">
      
    <div>
      <el-button v-if="SendStandChecksTableData.length!==0" size="small" type='primary' @click='sendDataCheckClickSecond()'>派发任务</el-button>
     
      <el-button  size="small"  @click='dialogSendStandChecksSecond = false'>取消</el-button>
    </div>
    </div>
    <div v-if="!showTableBottom" style="height:400px;display:flex;align-items: center;justify-content: center;color:#ccc">
       选择专业后可查看哪些设备可以被派发
      
    </div>
  </el-dialog>

  </div>
</template>

<script setup name="Project">

import { defineAsyncComponent, ref, reactive, onMounted, watch,onUnmounted } from "vue";
import { Plus, Delete, Warning,Upload,Tickets,CirclePlus,Download,MessageBox,DocumentChecked

 } from "@element-plus/icons-vue";
import { useProjectStore } from "/@/stores/project";
import PinYinMatch from "pinyin-match";
import { useEquipmentStore } from "../../stores/equipment";
/* 引入组件 */
const InfoCard = defineAsyncComponent(() =>
  import("./components/infoCard.vue")
);
const Rule = defineAsyncComponent(() => import("./components/rule.vue"));
const Schedule = defineAsyncComponent(() =>
  import("./components/schedule.vue")
);
const Note = defineAsyncComponent(() => import("./components/note.vue"));
const EquipList = defineAsyncComponent(() =>
  import("./components/equipList.vue")
);

import {
  IsProjHasUploadUniformRegulation,
  GetDepartmentUsersV2,
  IsAlreadyDistributed,
  IsAlreadyDistributed2,
  DownloadEquipmentLoadInformationTemp,
  BatchModifyEquipStatu,
  ExportEquipInfo,
} from "../../api/projectManage/projectList";

/* 引入API */
import {
  DeleteEquipsV2,
  GetCheckNozzleTable,
  getEquipments,
  GetEquipCustomAttributes,
  ExportZipForModelInput,
  ExportZipForModel,
  CreateCheckNozzleTable,
  addEquipV2,
  AddEquipmentsFromDataCenter,
  ImportEquipInfosV2,
  SendStandChecks,
  SendSafetyDesignCheck
} from "/@/api/equipment";
import { GetUnits,GetProjectUsers } from "/@/api/projectManage/projectList";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
/* 定义变量内容 */
let selectedProject = ref({});
const projectStore = useProjectStore();
let EquipmentStore = useEquipmentStore();
let equipments = ref([]);


let tableNum = ref(0)

// 设备数量
let tableDataSend = (data) => {
  tableNum.value = data.length
}

let proName = ref(null)

// 预留位置
onUnmounted(()=>{
  
})

// 发送人员信息拼音逻辑
let sendDataCheckOptions_py = ref([])
let matchFruit = (searchContent) => {
    if (searchContent) {
    let result = [];
    sendDataCheckOptions.value.forEach((item) => {
      // matchResult 的值为 true/false
      let matchResult = PinYinMatch.match(item.label, searchContent);
      if (matchResult) {
        result.push(item);
      }
    });
    sendDataCheckOptions_py.value = result;
  } else {
    sendDataCheckOptions_py.value = sendDataCheckOptions.value;
  }
  }


  // 派发任务
let sendDataCheckClick = async () => {
  let obj ={
    "proj_oid": projectStore.projectInfo.proj_oid,
    "equipInfos": SendStandChecksTableData.value.map(v=>{
      
      return {
        equip_name:v.equip_name,
        equip_no:v.equip_no,
        equip_dwg_no:v.equip_dwg_no,
        drawing_stage:v.drawing_stage,
      }
    }),
    "checkers": sendDataCheck.value,
    "sender": JSON.parse(localStorage.getItem("userMessage")).user_name
}
// 在发送之前进行校验 没有选择审查人就进行提示
if(obj.checkers.length==0){
  ElMessage({
   message: "请选择审查人",
   type: "error",
   })
   return
}
let res= await SendStandChecks(obj)
if(res == 'True'){
  ElMessage({
   message: "任务派发成功",
   type: "success",
   })
}else{
  ElMessage({
   message: "任务派发失败，请检查信息",
   type: "error",
   })
}

   dialogSendStandChecks.value = false
}




let sendDataCheck = ref([])
let sendDataCheckOptions = ref([])
let destEquipInfo = ref({
  unit_oid: "",
  equip_name: "",
  equip_no: "",
  equip_class: null,
  installation_mode: null,
  equip_dwg_no: "",
  vessel_type: "",
  equip_count: "",
  equip_dry_weight: "",
  special_material_weight: "",
  equip_designer: null,
  equip_checker: null,
  auditor: null,
  approver: null,
  
  drawing_stage:'工程图'
});
let destEquipInfoRules = ref({
  unit_oid: [{ required: true, message: "请输入主项号", trigger: "blur" }],
  equip_name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
  equip_no: [{ required: true, message: "请输入设备编号", trigger: "blur" }],
  equip_class: [
    { required: true, message: "请输入设备种类", trigger: "blur" },
  ],
  installation_mode: [
    { required: true, message: "请输入安装方式", trigger: "blur" },
  ],

  equip_dwg_no: [
    { required: false, message: "请输入设计图号", trigger: "blur" },
  ],
  vessel_type: [
    { required: false, message: "请输入设备类别", trigger: "blur" },
  ],
  equip_count: [{ required: false, message: "请输入台数", trigger: "blur" }],
  equip_dry_weight: [
    { required: false, message: "请输入空设备重量", trigger: "blur" },
  ],
  special_material_weight: [
    { required: false, message: "请输入特材重量", trigger: "blur" },
  ],
  equip_designer: [
    { required: false, message: "请输入设计人", trigger: "blur" },
  ],
  equip_checker: [
    { required: false, message: "请输入校核人", trigger: "blur" },
  ],
  auditor: [{ required: false, message: "请输入审批人", trigger: "blur" }],
  approver: [{ required: false, message: "请输入审定人", trigger: "blur" }],
});

// 关闭新建设备弹窗
let closeFrom = () => {
  destEquipInfoRef.value.resetFields();
};

let destEquipInfoRef = ref("");

let newDio = ref(false);



let sectionTableData = ref([]);
// 设备列表赋值
let tableList = (data) => {
  SendStandChecksTableData.value = data
  console.log(SendStandChecksTableData.value)
  sectionTableData.value = data;
};

let select_model_stage_class = ref([])
let custom_att1_val_class = ref('')
let select_equip_designer_class = ref('')
let select_installation_mode_class = ref('')
let select_equip_check_class = ref('')
// 选择是否进行筛选检索的字段
let SelectMajorFn = ({text,title}) => {
    if(title == 'SelectMajor'){
      SelectMajor.value = text
    }else if(title == 'equip_nameInput'){
      equip_nameInput.value  = text
    }else if(title == 'equipEquip_no'){
      SelectEquip_no.value = text
    }else if(title == 'equipEquip_class'){
      SelectEquip_class.value = text
    }else if(title=='drawing_stage'){
      drawing_stage.value = text

    }
    else if(title=='installation_mode_class'){
      select_installation_mode_class.value = text

    }
    else if(title=='equip_designer_class'){
      select_equip_designer_class.value = text

    }
    else if(title=='equip_checker_class'){
      select_equip_checker_class.value = text

    }
    else if(title=='auditor_class'){
      select_auditor_class.value = text

    }
    else if(title=='equip_check_class'){
     
      select_equip_check_class.value = text

    }else if (title=='custom_att1_val_class'){
      custom_att1_val_class.value = text
    }else if(title=='model_stage_class'){
    select_model_stage_class.value = text
   }
}

/*
   select_equip_checker_class.value,
    select_auditor_class.value,
    select_approver_class.value

*/

let SendStandChecksTableData = ref([])
let dialogSendStandChecks = ref(false)
let tableDataCopyData = []
// 设备派发逻辑
let clickSendStandChecks = async() => {
  // 在派发之前先进行一次数据拷贝 以免后续的操作对源数据进行污染
  tableDataCopyData = JSON.parse(JSON.stringify(SendStandChecksTableData.value))
  // 发送之前进行校验 看设备是否进行被发送
  if(SendStandChecksTableData.value.length>0){
   let dataTask = await IsAlreadyDistributed({
    proj_oid: projectStore.projectInfo.proj_oid,
    equips:SendStandChecksTableData.value.map(v=>{
       return {
        equip_no:v.equip_no,
        drawing_stage:v.drawing_stage,
       }
    })
 
   })
   
   if(dataTask.length==0){
  ElMessage({
  type:'success',
  message:'所有选中的任务都可被派发'

 })
 // 如果设备中包含了已经发送的
   }else if(dataTask.length>0&&dataTask.length!==SendStandChecksTableData.value.length){
    SendStandChecksTableData.value= SendStandChecksTableData.value.filter(item=>{

return dataTask.indexOf(item.equip_no) == -1;
 })
   ElMessage({
  type:'warning',
   message:`以下设备可以被派发，其中${ dataTask.length}台设备已经被派发`

 })
 // 如果设备中所有任务都被派发了
   }else if(dataTask.length>0&&dataTask.length==SendStandChecksTableData.value.length){
      ElMessage({
  type:'warning',
  message:'所有任务已经被派发，不可重复派发。'

 })
 SendStandChecksTableData.value = []
 return
   }
     dialogSendStandChecks.value = true
    let res = await GetDepartmentUsersV2({ dept: "equipment" })
    sendDataCheckOptions.value = res.map(v=>{
     return {
      label:v.user_name,
      value:v.user_name
     }
    })
    sendDataCheckOptions_py.value = sendDataCheckOptions.value
    // 如果没有选择设备  则进行提示
  }else{
    ElMessage({
      message: '请选择设备',
      type: 'warning'
    })
  }
 
}

// 关闭弹窗
let closeDio = () => {
  SendStandChecksTableData.value = tableDataCopyData
  sendDataCheck.value = []
  // SendStandChecksTableData.value = []
}

let dialogSendStandChecksSecond = ref(false)
let tableDataCopyDataSecond = []


let sendDataCheckSecond = ref(null)

// 关闭派发弹窗
let closeDioSecond = () => {
  proName.value = null
  sendDataCheckSecond.value = null
  SendStandChecksTableData.value = tableDataCopyDataSecond
}

// 发送安全审查派发逻辑
let sendDataCheckClickSecond = async() => {
   console.log(sendDataCheckSecond.value)
  if(!sendDataCheckSecond.value){
  ElMessage({
   message: "请选择审查人",
   type: "error",
   })
   return
}

if(!proName.value){
  ElMessage({
   message: "请选择专业",
   type: "error",
   })
   return
}
let res= await SendSafetyDesignCheck(
  projectStore.projectInfo.proj_oid,
  proName.value,
  sendDataCheckSecond.value,
  JSON.parse(localStorage.getItem("userMessage")).user_name,
  // 对派发信息进行处理
  (SendStandChecksTableData.value.map(v=>{
      return {
        drawing_stage:v.drawing_stage,
        equip_no:v.equip_no,
      }
    }))
)
if(res == 'True'){
  ElMessage({
   message: "任务派发成功",
   type: "success",
   })
}else{
  ElMessage({
   message: "任务派发失败，请检查信息",
   type: "error",
   })
}

   dialogSendStandChecksSecond.value = false
}

// 点击安全设计审查派发
let clickSendStandChecksSecond = async() => {
  
   if(SendStandChecksTableData.value.length>0){
    // 进行数据拷贝
    tableDataCopyDataSecond = JSON.parse(JSON.stringify(SendStandChecksTableData.value))
        dialogSendStandChecksSecond.value = true
    
 

 }else{
    ElMessage({
      message: '请选择设备',
      type: 'warning'
    })
  }
 
}


let clickSendStandChecksSecond2 =async () => {
  if(SendStandChecksTableData.value.length>0){
   let confrim = await ElMessageBox.confirm("确认修改所有勾选设备的设计状态为已完成？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
      size: "small",
    })
    if(confrim){
      let obj = {
      equip_check:'30',
      equip_checker:JSON.parse(localStorage.getItem("userMessage")).user_name,
      equip_oids:SendStandChecksTableData.value.map(item=>item.equip_oid)


    }
    getEquipmentList(
    projectStore.projectInfo.proj_oid,
    SelectMajor.value,
    SelectEquip_no.value,
    SelectEquip_class.value,
    equip_nameInput.value,
    drawing_stage.value,
    select_installation_mode_class.value,
    select_equip_designer_class.value,
    select_equip_checker_class.value,
    select_auditor_class.value,
    select_approver_class.value,
    select_equip_check_class.value,
    custom_att1_val_class.value,
    select_model_stage_class.value,
  );
    await BatchModifyEquipStatu(obj)
    ElMessage({
      message: '设备状态修改成功',
      type: 'success'
    })
    }
   
 }else{
    ElMessage({
      message: '请选择设备',
      type: 'warning'
    })
  }
}

let table_Loading = ref(true)

let showTableBottom = ref(false)
// input框进行检索
watch(proName,async()=>{
   if(proName.value){
    // 将之前拷贝的数据进行赋值
    SendStandChecksTableData.value = tableDataCopyDataSecond
    let dataTask = await IsAlreadyDistributed2(
    projectStore.projectInfo.proj_oid,
    proName.value,
    // 发送时处理数据
   ( SendStandChecksTableData.value.map(v=>{
      return {
         "equip_no": v.equip_no,
        "drawing_stage": v.drawing_stage
      }
    })),
   )
   showTableBottom.value = true
  // 发送前对数据进行校验
      if(dataTask.length==0){
  ElMessage({
  type:'success',
  message:'所有选中的任务都可被派发'

 })
 // 查看设备是否已经有被派发
   }else if(dataTask.length>0&&dataTask.length!==SendStandChecksTableData.value.length){
    
    SendStandChecksTableData.value = SendStandChecksTableData.value.filter(item => !dataTask.some(item2 => item.equip_no === item2.equip_no && item.drawing_stage === item2.drawing_stage));

   ElMessage({
  type:'warning',
  message:`以下设备可以被派发，其中${ dataTask.length}台设备已经被派发`

 })
 // 设备全部被派发
   }else if(dataTask.length>0&&dataTask.length==SendStandChecksTableData.value.length){
    SendStandChecksTableData.value = []
      ElMessage({
  type:'warning',
  message:'所有任务已经被派发，不可重复派发。'

 })
 return
   }
 

   
    let res = await GetDepartmentUsersV2({ dept: "equipment" })
    sendDataCheckOptions.value = res.map(v=>{
     return {
      label:v.user_name,
      value:v.user_name
     }
    })
    sendDataCheckOptions_py.value = sendDataCheckOptions.value
   

   }else{
    showTableBottom.value = false
   }
})

let select_auditor_class = ref([])
watch(
  () => EquipmentStore.UpgradeEquipCount,
  () => {
    getEquipmentList(
    projectStore.projectInfo.proj_oid,
    SelectMajor.value,
    SelectEquip_no.value,
    SelectEquip_class.value,
    equip_nameInput.value,
    drawing_stage.value,
    select_installation_mode_class.value,
    select_equip_designer_class.value,
    select_equip_checker_class.value,
    select_auditor_class.value,
    select_approver_class.value,
    select_equip_check_class.value,
    custom_att1_val_class.value,
    select_model_stage_class.value,
  );
  }
);

// 新增设备
let handleCopyEquip = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      // 判断是否有数据中心的标识
      if(showCenter.value){
// 保存数据
      let res =  await addEquipV2({
        ...destEquipInfo.value,
        proj_oid: selectedProject.value.proj_oid,
      });
      if(res === 'True'){
        ElMessage({
        message: "新增成功",
        type: "success",
      });
      }else{
        ElMessage({
        message: "新增失败",
        type: "error",
      });
      }
  
      newDio.value = false;
      EquipmentStore.UpgradeEquipCount += 1;
      }else{
        // 从数据中心获取设备数据
     await AddEquipmentsFromDataCenter(
      {
        proj_oid: selectedProject.value.proj_oid,
        proj_no:selectedProject.value.proj_no,
        unit_oid:(unit_oidOptions.value.find(v=>v.value == destEquipInfo.value.unit_oid)).value,
        unit_no:(unit_oidOptions.value.find(v=>v.value == destEquipInfo.value.unit_oid)).label
      }
     )
     ElMessage({
        message: "数据拉取成功",
        type: "success",
      });
      newDio.value = false;
      EquipmentStore.UpgradeEquipCount += 1;

      }
      
    }
  });
};


// 文件上传请求
let uploadRequest =async (uploadFile) => {

  ElMessageBox.confirm("上传前请检查导入表格，用户设备所属主项必须已创建，表中设备位号和设备名称不能为空，已存在设备不能重复导入。", "提示", {
      confirmButtonText: "继续上传",
      cancelButtonText: "取消上传",
      type: "warning",
      size: "small",
    }).then(async()=>{
      // 上传后将仓库里面的值变为True 标记文件已经被上传
      EquipmentStore.computedCaCount  = true
      let formData = new FormData();
    //传给后台接收的名字 file
    formData.append("file", uploadFile.file);
    // 发送请求正式上传
    let res= await ImportEquipInfosV2(formData,projectStore.projectInfo.proj_oid)
 
     if(res == 'True'){
      ElMessage({
      message: "上传成功",
      type: "success",
  
     })
   
     }else{
      ElMessage({
      message: res.data,
      type: "error",
  
     })
     }
     // 上传成功后更新数据  使前后端保持一致
     getEquipmentList(
    projectStore.projectInfo.proj_oid,
    SelectMajor.value,
    SelectEquip_no.value,
    SelectEquip_class.value,
    equip_nameInput.value,
    drawing_stage.value,
    select_installation_mode_class.value,
    select_equip_designer_class.value,
    select_equip_checker_class.value,
    select_auditor_class.value,
    select_equip_check_class.value,
    custom_att1_val_class.value,
    select_model_stage_class.value,
  );

 setTimeout(()=>{
  // 当文件上传成功后 将store中的文件标记删除
  EquipmentStore.computedCaCount  = false
 },1000)
    })

    
}




let unit_oidOptions = ref([]);

let showCenter = ref(false)


// 获取数据中心设备
let newDioFn = async (str) => {
  
  if(!str){
    showCenter.value = true
    let res = await GetUnits({ proj_oid: selectedProject.value.proj_oid });
  if(res){
    unit_oidOptions.value = res.map((v) => {
    return {
      value: v.unit_oid,
      label: v.unit_no,
    };
  });
    }else{
      unit_oidOptions.value = [];
    }
 
    // 获取设备设计人员下拉框
    equip_designerOptions.value = (await GetProjectUsers({ proj_oid: selectedProject.value.proj_oid, user_role: '设计人' })).map((v) => ({label:v.user_name,value:v.user_name}))
    // 获取设备设计人员拼音赋值
    equip_designerOptions_PY.value = equip_designerOptions.value
   // 获取设备检查人员
    equip_checkerOptions.value =  (await GetProjectUsers({ proj_oid: selectedProject.value.proj_oid, user_role: '校核人' })).map((v) => ({label:v.user_name,value:v.user_name}))
   // 获取设备检查人员拼音赋值
    equip_checkerOptions_PY.value = equip_checkerOptions.value
     // 获取设备审核人员
    auditorOptions.value = (await GetProjectUsers({ proj_oid: selectedProject.value.proj_oid, user_role: '审核人' })).map((v) => ({label:v.user_name,value:v.user_name}))
    // 获取设备审核人员拼音赋值
    auditorOptions_PY.value = auditorOptions.value
     // 获取设备校核人员
    approverOptions.value = (await GetProjectUsers({ proj_oid: selectedProject.value.proj_oid, user_role: '审定人' })).map((v) => ({label:v.user_name,value:v.user_name}))
    // 获取设备校核人员拼音赋值
    approverOptions_PY.value = approverOptions.value
    newDio.value = true;
  }else{
    showCenter.value = false
    let res = await GetUnits({ proj_oid: selectedProject.value.proj_oid });
  if(res){
    unit_oidOptions.value = res.map((v) => {
    return {
      value: v.unit_oid,
      label: v.unit_no,
    };
  });
    }else{
      unit_oidOptions.value = [];
    }

    newDio.value = true;
  }
  
};
let approverOptions = ref([])
let auditorOptions = ref([])
let equip_designerOptions = ref([])
let equip_checkerOptions = ref([])
let SelectEquip_no = ref([]);
let equipEquip_no = ref([]);

let SelectEquip_class = ref([]);
let equipEquip_class = ref([]);

let equip_designerOptions_PY = ref([])
// 拼音下拉框逻辑
let matchFruitFirst = (searchContent) => {
  console.log(searchContent)
  if (searchContent) {
    let result = [];
    equip_designerOptions.value.forEach((item) => {
      // matchResult 的值为 true/false
      let matchResult = PinYinMatch.match(item.label, searchContent);
      console.log(matchResult)
      if (matchResult) {
        result.push(item);
      }
    });
    console.log(result)
    equip_designerOptions_PY.value = result;
    console.log(equip_designerOptions_PY.value)
  } else {
    equip_designerOptions_PY.value = equip_designerOptions.value;
  }
}

let equip_checkerOptions_PY = ref([])
// 拼音下拉框逻辑
let matchFruitSecond = (searchContent) => {
  if (searchContent) {
    let result = [];
    equip_checkerOptions.value.forEach((item) => {
      // matchResult 的值为 true/false
      let matchResult = PinYinMatch.match(item.label, searchContent);
      if (matchResult) {
        result.push(item);
      }
    });
    equip_checkerOptions_PY.value = result;
  } else {
    equip_checkerOptions_PY.value = equip_checkerOptions.value;
  }
}


let auditorOptions_PY = ref([])
let matchFruitThird = (searchContent) => {
  if (searchContent) {
    let result = [];
    auditorOptions.value.forEach((item) => {
      // matchResult 的值为 true/false
      let matchResult = PinYinMatch.match(item.label, searchContent);
      if (matchResult) {
        result.push(item);
      }
    });
    auditorOptions_PY.value = result;
  } else {
    auditorOptions_PY.value = auditorOptions.value;
  }
}


let approverOptions_PY = ref([])
let matchFruitFour = (searchContent) => {
  if (searchContent) {
    let result = [];
    approverOptions.value.forEach((item) => {
      // matchResult 的值为 true/false
      let matchResult = PinYinMatch.match(item.label, searchContent);
      if (matchResult) {
        result.push(item);
      }
    });
    approverOptions_PY.value = result;
  } else {
    approverOptions_PY.value = approverOptions.value;
  }
}




// 监听项目是否切换 如果项目切换  数据也需要一起进行切换
watch(
  () => projectStore.projectInfo,
 async (newVal, oldVal) => {
  
    selectedProject.value = newVal;
 
    // 更新设备列表
    getEquipmentList(newVal.proj_oid);

    setTimeout(async()=>{
      let userData = JSON.parse(localStorage.getItem("userMessage"))
    // 为专业负责人或者专业组长时 需要查看是否上传文件
  if(userData.roles.includes('专业负责人')||userData.roles.includes('专业组长')){
       
       let res = await IsProjHasUploadUniformRegulation({proj_oid:selectedProject.value.proj_oid})
       if(res?.data == 'False'){
       
        if(hasUP.value){
          showTips.value.push(true)
          
        }else{
          hasUP.value = true
        }
       
       }else{
        showTips.value.push(false)
       
       }
     

  }
    },500)
  }
);

let SelectMajor = ref([]);
let equipOptions = ref([]);

let equip_nameInput = ref([]);
let drawing_stage = ref([])
let nameOptions = ref([]);
let select_equip_checker_class = ref([])

let select_approver_class = ref([])

// 监听这几个字段  用以下拉筛选 从后台获取数据
watch([SelectMajor, SelectEquip_no, SelectEquip_class, equip_nameInput,drawing_stage,select_installation_mode_class,select_equip_designer_class,select_equip_checker_class,select_auditor_class,select_approver_class,select_equip_check_class,custom_att1_val_class,select_model_stage_class], () => {
  getEquipmentList(
    projectStore.projectInfo.proj_oid,
    SelectMajor.value,
    SelectEquip_no.value,
    SelectEquip_class.value,
    equip_nameInput.value,
    drawing_stage.value,
    select_installation_mode_class.value,
    select_equip_designer_class.value,
    select_equip_checker_class.value,
    select_auditor_class.value,
    select_approver_class.value,
    select_equip_check_class.value,
    custom_att1_val_class.value,
    select_model_stage_class.value,
  );
});

// 获取下拉框（格式化） 重构想要的数据结构
let getOptions = (data, str) => {
  return [...new Set(data.map((v) => v[str]))]
    .filter((v) => {
      if (v) {
        return v;
      }
    })
    .map((v) => {
      return {
        value: v,
        label: v,
      };
    });
};
let equip_checker_class = ref([])
let auditor_class = ref([])
let approver_class = ref([])
let equip_designer_class = ref([])
let installation_mode_class = ref([])
let tableHeader  = ref('')
let custom_att1_val_option = ref([])
/* 定义函数内容 */
async function getEquipmentList(
  proj_oid,
  SelectMajorStr = [],
  SelectEquip_no = [],
  SelectEquip_class = [],
  equip_nameInput = [],
  drawing_stage = [],
  installation_mode=[],
  equip_designer=[],
  equip_checker =[],
  auditor = [],
  approver =[],
  equip_check=[],
  custom_att1_val=[],
  model_stage=[],
) {

  let tableHeaderStr = await GetEquipCustomAttributes({proj_oid})
  tableHeader.value = tableHeaderStr.custom_att1
  
  // 获取所有设备
  let data = await getEquipments({
    proj_oid,
    equip_user: JSON.parse(localStorage.getItem("userMessage")).user_name,
    authCode: localStorage.getItem("authCode"),
    custom_att1: tableHeader.value
  });
  table_Loading.value = false

 
  // 获取需要的下拉框
  equipOptions.value = getOptions(data, "equip_unit_no");
  equipEquip_no.value = getOptions(data, "equip_no");
  equipEquip_class.value = getOptions(data, "equip_class");
  installation_mode_class.value = getOptions(data, "installation_mode");
  nameOptions.value = getOptions(data, "equip_name");
  equip_designer_class.value = getOptions(data, "equip_designer");
  equip_checker_class.value = getOptions(data, "equip_checker");
  auditor_class.value = getOptions(data, "auditor");
  approver_class.value = getOptions(data, "approver");
  custom_att1_val_option.value = getOptions(data, "custom_att1_val");
 
  // 定义筛选条件
  const filters = {
    equip_unit_no: SelectMajorStr, // num 符合 'R1' 或 'R2'
    equip_no: SelectEquip_no, // id 符合 1
    equip_class: SelectEquip_class,
    equip_name: equip_nameInput,
    drawing_stage:drawing_stage,
    installation_mode:installation_mode,
    equip_designer:equip_designer,
    equip_checker:equip_checker,
    auditor:auditor,
    approver:approver,
    equip_check:equip_check,
    custom_att1_val:custom_att1_val,
    model_stage:model_stage,
  };
 
 // 对数据进行筛选
  equipments.value = multiFilter(JSON.parse(JSON.stringify(data)), filters);
  
}

// 对数据进行的筛选算法
function multiFilter(array, filters) {
  const filterKeys = Object.keys(filters);

  return array.filter((item) => {
    return filterKeys.every((key) => {
      if (!filters[key].length) return true;
      return !!~filters[key].indexOf(item[key]);
    });
  });
}


// 下载上传文件模板
let downLoadFiles = async() => {
  let res = await DownloadEquipmentLoadInformationTemp()
  let filename = res.headers; //下载后文件名
  let filename2 = ""; //下载后文件名
  filename = filename["content-disposition"];
  filename = window.decodeURI(filename);
  filename2 = filename.split(";")[1].split("filename*=UTF-8''")[1];
  filename = filename.split(";")[1].split("filename=")[1];
  const link = document.createElement("a"); // 创建a标签
  const blo = new Blob([res.data], { type: res.data.type }); // 设置下载格式
  link.style.display = "none";
  const url = window.URL.createObjectURL(blo);
  console.log(url);
  link.href = url;
  if (filename == undefined) {
    filename = filename2;
  }
  link.download = filename;

  // link.setAttribute('download', "fileName")3
  document.body.appendChild(link);
  link.click(); // 触发下载
  window.URL.revokeObjectURL(url); // 释放掉blob对象
  document.body.removeChild(link);
}


let donwnloadEquipmentLoadInformationTemp = async() => {
 let res = await ExportEquipInfo({proj_oid:projectStore.projectInfo.proj_oid})
  let filename = res.headers; //下载后文件名
  let filename2 = ""; //下载后文件名
  filename = filename["content-disposition"];
  filename = window.decodeURI(filename);
  filename2 = filename.split(";")[1].split("filename*=UTF-8''")[1];
  filename = filename.split(";")[1].split("filename=")[1];
  const link = document.createElement("a"); // 创建a标签
  const blo = new Blob([res.data], { type: res.data.type }); // 设置下载格式
  link.style.display = "none";
  const url = window.URL.createObjectURL(blo);
  console.log(url);
  link.href = url;
  if (filename == undefined) {
    filename = filename2;
  }
  link.download = filename;

  // link.setAttribute('download', "fileName")3
  document.body.appendChild(link);
  link.click(); // 触发下载
  window.URL.revokeObjectURL(url); // 释放掉blob对象
  document.body.removeChild(link);

}

// 删除设备
let deleteEquipment = () => {

  if (sectionTableData.value == 0) {
    ElMessage({
      message: "请勾选设备",
      type: "error",
    });
    return;
  }

  ElMessageBox.confirm("此操作将永久删除勾选设备和设备关联的所有数据，确认删除？", "警告", {
    type: "warning",
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    buttonSize: "small",
  }).then(async () => {
    EquipmentStore.computedCaCount  = true
    await DeleteEquipsV2({equip_oids:sectionTableData.value.map(v=>v.equip_oid)})
        ElMessage({
          message: "删除成功",
          type: "success",
        });
        EquipmentStore.UpgradeEquipCount += 1;
        EquipmentStore.computedCaCount  = false
  });
};





let showTips = ref([])
// 监听是否上传了统一规定 并存起来
watch(showTips,()=>{
 
  let arr = [...new Set(showTips.value)]
  if(arr[arr.length-1]){
    ElMessageBox.alert('该项目没有上传统一规定，请前往项目管理上传统一规定', '上传统一规定', {
   
   confirmButtonText: '确定',

})
// showTips.value = []
  }
},{deep:true})


let hasUP = ref(true)
onMounted(async() => {
  
  setTimeout(()=>{
    selectedProject.value = projectStore.projectInfo;
    setTimeout(async()=>{
      // 查看是否上传了统一规定 并且让请求延迟到最后完成 以此判断弹窗弹出的时机在表格渲染完成之后
      let userData = JSON.parse(localStorage.getItem("userMessage"))
      console.log(projectStore.projectInfo.proj_oid,userData)
  if(userData.roles.includes('专业负责人')||userData.roles.includes('专业组长')){
       let res = await IsProjHasUploadUniformRegulation({proj_oid:projectStore.projectInfo.proj_oid})
       if(res?.data == 'False'){
        console.log('False')
        showTips.value.push(true)
        hasUP.value = false
       }else{
        showTips.value.push(false)
       }
     

  }
    },400)
// 获取当前项目设备列表

getEquipmentList(projectStore.projectInfo.proj_oid);
  },200)
});
</script>

<style scoped lang="scss">
.project-infor-cards {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.equip-list {
  min-height: calc(100vh - 170px);
  background-color: #fff;
}

.equip-title_span {
  font-weight: bold;
  margin-right: auto;
  font-size: 1.5em;
  padding-left: 8px;
  border-left: 6px solid #67c23a;
}
.equip-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 8px;
  margin-bottom: 8px;

  .el-button-group {
    display: flex;
    align-items: center;

    margin-left: 16px;
  }
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.img_hualu{
  position: absolute;
    transform: scale(0.5) rotate(0deg);
    top: -13px;
    right: -102px;
    z-index: 88;
    opacity: .7;
}
.button_mt_margin_right{
  margin-right: 10px!important;
}
</style>
